//
//  WBOAuthViewController.swift
//  Weibo
//
//  Created by wade on 17/2/23.
//  Copyright © 2017年 wade. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBOAuthViewController: UIViewController {

    lazy var webview = UIWebView()
    
    override func loadView() {
        
        view = webview
        
        view.backgroundColor = UIColor.white

        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 15, target: self, action: #selector(close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
        // 设置代理
        webview.delegate = self
        
        // 设置导航栏
        title = "登录新浪微博"
        
        
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(AppUri)"
        
        guard let url = URL(string: urlString) else{
            
            return
        }
        
        let urlrequest = URLRequest(url: url)
        
        webview.loadRequest(urlrequest)

    }

    func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    func autoFill(){
    
        let js = "document.getElementById('userId').value = 'xuyg0215@sina.com';document.getElementById('passwd').value = 'Abcde456852'"
        
        webview.stringByEvaluatingJavaScript(from: js)
        
    }

}

extension WBOAuthViewController:UIWebViewDelegate{

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(AppUri) == false {
            return true
        }
        
        // print("加载请求 --- \(request.url?.absoluteString)")
        // query 就是 URL 中 `?` 后面的所有部分
        // print("加载请求 --- \(request.url?.query)")
        // 2. 从 http://baidu.com 回调地址的`查询字符串`中查找 `code=`
        //    如果有，授权成功，否则，授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            
            return false
        }
        
        // 3. 从 query 字符串中取出 授权码
        // 代码走到此处，url 中一定有 查询字符串，并且 包含 `code=`
        // code=15be12d79321e474c599210ef637c978
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码 - \(code)")
        
        WBNetworkManager.shared.loadAccessToken(code: code) { (bool) in
            if bool {
                SVProgressHUD.showInfo(withStatus: "登陆完成")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                self.close()
                
                
                
            }
            else
            {
                SVProgressHUD.showInfo(withStatus: "登陆失败")
            }
        }
        
       
        
        return false
    }

    
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}

